<template>
  <el-dialog
    top="30px"
    width="80%"
    class="dialog-sm"
    append-to-body
    title="项目审查"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-steps :active="stepActive" simple finish-status="success" class="mb-3">
      <el-step title="1、选择审查项目" icon="el-icon-tickets"></el-step>
      <el-step title="2、填写意见" icon="el-icon-edit"></el-step>
    </el-steps>
    <div v-show="stepActive === 0">
      <c-table
        border
        v-loading="loading"
        class="table-sm"
        ref="multipleTable"
        name="table"
        height="62vh"
        row-key="customer_related_id"
        :columns="tableColumns"
        :data="tableData"
        @selection-change="handleSelectionChange"
      ></c-table>
      <div class="query-pagination">
        <div>
          <el-checkbox
            v-model="allChecked"
            label="全选所有页"
            :disabled="loading"
            @change="handleSelectAll"
          ></el-checkbox>
          <span class="ml-1 text-muted">
            （已选择 {{ selectLen }} 个项目，总金额 {{ selectFunds }} 万元）
          </span>
        </div>
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page.sync="pageParams.index"
          :page-size="pageParams.size"
          :total="tableCount"
          @current-change="getPageData"
        ></el-pagination>
      </div>

      <div class="text-center mt-3">
        <el-button
          type="primary"
          class="btn-long"
          :disabled="!tableData.length"
          :loading="loading"
          @click="handleSelectFinish"
        >
          <span>完成选择</span>
          <i class="el-icon-arrow-right"></i>
        </el-button>
      </div>
    </div>
    <div v-show="stepActive === 1">
      <div style="height: 67vh" class="border p-3">
        <el-form :model="opinionForm" :rules="rules" ref="opinionForm" label-width="120px">
          <el-form-item label="项目数量">
            <span>{{ multipleSelection.length }}个</span>
          </el-form-item>
          <el-form-item label="贷款总额">
            <span>{{ selectFunds }} 万元</span>
          </el-form-item>
          <el-form-item label="意见" prop="opinion">
            <el-input type="textarea" :rows="10" v-model="opinionForm.opinion"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="text-center mt-3">
        <el-button :loading="loading" @click="stepActive--">
          <i class="el-icon-arrow-left"></i>
          <span>重新选择</span>
        </el-button>
        <el-button type="primary" class="btn-long" :loading="loading" @click="handleApprovalFinish">
          完成
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { hndBaseTableColumns } from '@/credit/views/province/hnd/Recommend'
import { strip } from '@vimi/utils-tool'
// import { guid } from '@/common/plugins/tools/string'

export default {
  components: {},
  props: {
    visible: Boolean,
  },
  data() {
    return {
      stepActive: 0,
      tableName: 'datum_one_county_industry',
      pageParams: {
        index: 1,
        size: 10,
      },
      tableCount: 0,
      totalPages: 0,

      params: {
        'service_id.eq': '',
        'import_status.eq': 1,
        'update_apply.eq': 0,
        'res_status_corp.eq': 0,
        'res_status_point.eq': 0,
        'project_status.neq': 3,
        'is_history.eq': 0,
        fields: [
          'customer_related_id',
          'service_id',
          'import_status',
          'update_apply',
          'res_status_corp',
          'res_status_point',
          'project_status',
          'is_history',
          'customer_name',
          'org_class_name',
          'main_business',
          'corp_phone',
          'bank_name',
          'load_date',
          'load_end_date',
          'warranty_period',
          'warranty_amount',
          'funds_use_dir',
        ],
      },
      order: {},
      loading: false,
      tableData: [],
      allData: [],
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            width: 55,
            reserveSelection: true,
          },
        },
        ...hndBaseTableColumns,
      ],
      multipleSelection: [],
      allChecked: false,
      opinionForm: {
        opinion: '',
      },
      rules: {
        opinion: [{ required: true, message: '请填写意见', trigger: 'blur' }],
      },
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    selectLen() {
      return this.multipleSelection.length
    },
    selectFunds() {
      let funds = 0
      for (const item of this.multipleSelection) {
        funds += item.warranty_amount
      }
      return strip(funds)
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.getData()
      }
    },
  },
  created() {
    this.params['service_id.eq'] = this.clientId
  },
  mounted() {},
  methods: {
    beforeClose() {
      this.stepActive = 0
      Object.keys(this.opinionForm).forEach(key => {
        this.opinionForm[key] = ''
      })
      this.$emit('update:visible', false)
    },
    async getData() {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, this.order)
      )
      this.loading = false

      this.allData = ((res && res.data) || []).map(this.dataAdapter)
      this.tableCount = this.allData.length
      this.totalPages = Math.ceil(this.tableCount / this.pageParams.size)
      this.getPageData(1)
    },
    dataAdapter(item) {
      item.loadDate = this.$utils.dateFormat(item.load_date, 'yyyy-MM-dd')
      item.loadEndDate = this.$utils.dateFormat(item.load_end_date, 'yyyy-MM-dd')
      item.statusLabel = '已通过'

      return item
    },

    // 前端分页
    getPageData(index) {
      this.tableData = []
      this.pageParams.index = index
      const start = (index - 1) * this.pageParams.size
      const end = this.totalPages <= index ? this.allData.length : start + this.pageParams.size
      for (let i = start; i < end; i++) {
        this.tableData.push(this.allData[i])
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      this.allChecked = this.selectLen === this.allData.length
    },
    handleSelectAll(val) {
      const $tableRef = this.$refs.multipleTable.$refs.table
      if (!$tableRef) return

      if (val) {
        // this.allData.forEach(row => $tableRef.store.toggleRowSelection(row, true, false))
        $tableRef.store.states.selection = this.allData.slice()
        $tableRef.$emit('selection-change', this.allData.slice())
        $tableRef.store.updateAllSelected()
      } else {
        $tableRef.clearSelection()
      }
    },

    handleSelectFinish() {
      if (!this.selectLen) {
        return this.$message.error(this.tableData.length ? '请先选择审查项目' : '暂无可审查的项目')
      }
      this.stepActive++
    },
    handleApprovalFinish() {
      this.$refs.opinionForm.validate(valid => {
        if (valid) {
          this.putApproval()
        } else {
          this.$message.error('请填写意见')
        }
      })
    },
    putApproval() {
      const date = this.$utils.dateFormat(new Date())

      let bankCount = 0
      let banks = {}
      for (const project of this.multipleSelection) {
        if (!banks[project.bank_id || project.bank_name || 'none']) {
          bankCount++
        }
      }

      const masterData = {
        res_status_point: 1,
        res_date_point: date,
        res_option_point: this.opinionForm.opinion,
        res_person_point: this.user.realName,
        project_count: this.selectLen,
        bank_count: bankCount,
        service_id: this.clientId,
      }
      const slaveData = this.multipleSelection.map(it => ({
        customer_related_id: it.customer_related_id,
      }))
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'review_approval_batch',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'review_approval_batch_detail',
      }

      // 关联添加，由后端自动同步 review_approval_batch_id
      this.loading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(res => {
          this.$emit('success', res)
          this.$message.success('提交成功！')
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('提交项目审查失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .el-step__title {
  font-size: 1rem;
  line-height: 1.4;
}
</style>
